package com.zhuqi.proto.cost;

import com.zhuqi.proto.build.ChatMessageBuild;
import com.zhuqi.proto.build.HeatBeatProtoBuild;
import com.zhuqi.proto.build.LogOutMessageBuild;
import com.zhuqi.proto.build.LoginMessageProtoBuild;

import java.util.HashMap;
import java.util.function.Function;

import static com.zhuqi.proto.cost.MessageProtocolBufEnum.FunctionMap.functionHashMap;

/**
 * <p>消息业务类型枚举</p>
 * @author zhuqi
 * @since 2023/3/14 13:13
 * code 业务编码
 * function 对应业务类型解码方法
 */
public enum MessageProtocolBufEnum {

	/**
	 * 登陆
	 */
	LOGIN_REQUEST_MESSAGE(0,
			array -> LoginMessageProtoBuild.parseArrayTOLoginRequestMessage((byte[]) array)),
	LOGIN_RESPONSE_MESSAGE(1,
			array -> LoginMessageProtoBuild.parseArrayTOLoginResponseMessage((byte[]) array)),

	/**
	 * 单聊消息
	 */
	CHAT_REQUEST_MESSAGE(3,
			array -> ChatMessageBuild.parseArrayTOChatRequestMessage((byte[]) array)),
	CHAT_RESPONSE_MESSAGE(4,
			array -> ChatMessageBuild.parseArrayTOChatResponseMessage((byte[]) array)),

	/**
	 * 退出登陆
	 */
	LOG_OUT_REQUEST_MESSAGE(5,
			array -> LogOutMessageBuild.parseArrayTOLogOutMessageRequest((byte[]) array)),
	LOG_OUT_RESPONSE_MESSAGE(6,
			array -> LogOutMessageBuild.parseArrayTOLogOutMessageResponse((byte[]) array)),

	/**
	 * 心跳消息
	 */
	HEARTBEAT_REQUEST_MESSAGE(9998,
			array -> HeatBeatProtoBuild.parseArrayTOHeartBeatRequest((byte[]) array)),
	HEARTBEAT_RESPONSE_MESSAGE(9999,
			array -> HeatBeatProtoBuild.parseArrayTOHeartBeatResponse((byte[]) array)),
	;


	private Integer code;

	private Function function;

	MessageProtocolBufEnum(Integer code, Function function) {
		this.code = code;
		this.function = function;
	}


	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public Function getFunction() {
		return function;
	}

	public void setFunction(Function function) {
		this.function = function;
	}

	public static Function getFunctionByCode(int business) {
		Function function = functionHashMap.get(business);
		if (function == null) {
			throw new RuntimeException("为找到业务码相关的编解码器");
		}
		return function;
	}


	static class FunctionMap {

		// 存放<业务码，对应的转码函数>
		public static HashMap<Integer, Function> functionHashMap = new HashMap<>(values().length);

		// 初始化 函数 Map
		static {
			FunctionMap.initMap();
		}

		public static void initMap(){
			MessageProtocolBufEnum[] values = values();
			for (MessageProtocolBufEnum value : values) {
				functionHashMap.put(value.getCode(), value.getFunction());
			}
		}
	}
}
